package com.ohc.leetcode.二叉树;

import com.ohc.leetcode.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * 2022年4月30日15:36:04
 */
public class 在每个树行中找最大值515 {
    static List<List<Integer>> lists = new ArrayList<>();

    public static List<Integer> largestValues(TreeNode root) {
        List<Integer> arrayList = new ArrayList<>();
        if (root == null) {
            return arrayList;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        // 层序遍历
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int len = queue.size();
            while (len > 0) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                len--;
            }
            // 到这里len <=0 说明一层遍历完了。
            lists.add(list);
        }
//        List<Integer> arrayList = new ArrayList<>();
        for (int i = 0; i < lists.size(); i++) {
            List<Integer> list = lists.get(i);
            Integer temp = list.get(0);
            for (int i1 = 0; i1 < list.size(); i1++) {
                // 大于i1+1 是为了防止只有1个元素的时候，下面的i1+1 索引小标越界异常
                if (list.size() > i1 + 1 && list.get(i1 + 1) > temp) {
                    temp = list.get(i1 + 1);
                }
            }
            arrayList.add(temp);
        }
        if (arrayList.size() == 0) {
            return null;
        } else {
            return arrayList;

        }
    }

    public static void main(String[] args) {
        TreeNode treeNode1 = new TreeNode();
        TreeNode treeNode2 = new TreeNode();
        TreeNode treeNode3 = new TreeNode();
        treeNode1.right = treeNode2;
        treeNode1.left = treeNode3;
        treeNode2.right = null;
        treeNode2.left = null;
        treeNode3.right = null;
        treeNode3.left = null;
        treeNode1.val = 1;
        treeNode2.val = 2;
        treeNode3.val = 3;
        largestValues(treeNode1);
    }
}
